package com.bsoft.gol.hbs.dao;

import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import pcn.bean.hpi.PcnBaseHpi;
import pcn.enums.ViewStatus;

import java.util.List;

public abstract class PcnBaseHpiDAO extends HibernateSupportDelegateDAO<PcnBaseHpi> {
	public PcnBaseHpiDAO() {
		this.setKeyField("hpiId");
	}

	public PcnBaseHpi findPcnBasehpiById(final Integer hpiId){
		HibernateStatelessResultAction<PcnBaseHpi> action = new AbstractHibernateStatelessResultAction<PcnBaseHpi>() {
			@Override
			public void execute(StatelessSession ss) throws Exception {
				String sql = "from PcnBaseHpi where hpiId=:hpiId";
				Query query = ss.createQuery(sql.toString());
				query.setInteger("hpiId", hpiId);
				setResult((PcnBaseHpi)query.uniqueResult());
			}
		};
		HibernateSessionTemplate.instance().execute(action);
		return action.getResult();
	}

	@DAOMethod(sql = "from PcnBaseHpi  where hpiId not in (select hpiId from PcnHpiResident  where mpiId=:mpiId) ")
	public abstract List<PcnBaseHpi> findWaitSyncPcnBasehpiByMpiId(@DAOParam("mpiId") String mpiId);

	@DAOMethod(sql = "from PcnBaseHpi where hpiCode=:hpiCode")
	public abstract List<PcnBaseHpi> findPcnBasehpiByHpiCode(@DAOParam("hpiCode") String hpiCode);

	@DAOMethod(sql = "from PcnBaseHpi where typeId=:typeId")
	public abstract List<PcnBaseHpi> findPcnBasehpiByTypeId(@DAOParam("typeId") int typeId);

	/**
	 * 删除健康指标
	 * @param hpiId
	 */
	@DAOMethod(sql = "delete PcnBaseHpi where hpiId=:hpiId ")
	public abstract void updateBaseHpi(@DAOParam("hpiId") int hpiId);

	@DAOMethod(sql = "from PcnBaseHpi")
	public abstract List<PcnBaseHpi> findAll();

	public  List<PcnBaseHpi> findAllByStatus(){
		HibernateStatelessResultAction<List<PcnBaseHpi>> action = new AbstractHibernateStatelessResultAction<List<PcnBaseHpi>>() {
			@Override
			public void execute(StatelessSession ss) throws Exception {
				String sql = "from PcnBaseHpi b  where b.status=:status and b.typeId in(select t.typeId from PcnHpiType t where t.status=:status)";
				Query query = ss.createQuery(sql.toString());
				//query.setString("hpiId", "hpiId");
				query.setString("status", ViewStatus.enable.getValue());
				setResult((List<PcnBaseHpi>)query.list());
			}
		};
		HibernateSessionTemplate.instance().execute(action);
		return action.getResult();
	}

}
